import { Injectable } from '@angular/core';
import { Device} from '@ionic-native/device/ngx';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer/ngx';
import { HttpBase } from './http.base';
import { ToastService } from './toast.service';

@Injectable({
    providedIn: 'root'
})

export class TransferService extends HttpBase {

    endPointUrl: string;
    options: any = {};

    constructor(public device: Device, private transfer: FileTransfer, private toastSrv: ToastService) {
        super();
        this.endPointUrl = this.getEndPoint(!!this.device.platform);
    }

    public setUrl(url: string) {
        this.options.url = url;
        return this;
    }

    public setPath(path: string) {
        this.options.path = path;
        return this;
    }

    public setFieldName(fieldName: string) {
        this.options.fieldName = fieldName;
        return this;
    }

    public setFileName(fileName: string) {
        this.options.name = fileName;
        return this;
    }

    public setParams(params: any) {
        this.options.params = params;
        return this;
    }

    public setFile(file: any) {
        this.options.file = file;
        return this;
    }

    public parseFile() {
        if (Array.isArray(this.options.file)) {
            this.options.file = this.options.file[0];
        }
        const lastIndex = this.options.file.lastIndexOf('/');
        this.options.name = this.options.file.substr(lastIndex + 1);
        return this;
    }

    async upload() {
        const { url, path, params, file, fieldName, name } = this.options;

        const headers: any = {};
        const authToken = localStorage.getItem('auth-token');
        if (authToken) {
            headers.Authorization = authToken;
        }

        const options: FileUploadOptions = {
            fileKey: fieldName,
            fileName: name,
            params: { ...params },
            headers: { ...headers }
        };

        try {
            const requestUrl = url || this.endPointUrl + path;
            const result = await this.transfer.create().upload(file, requestUrl, options).then(resp => JSON.parse(resp.response));
            if (result.status > 0) {
                this.toastSrv.showToast(result.message);
            }
            return result;
        } catch (error) {
            // alert(JSON.stringify(error));
            this.toastSrv.showToast(error.message);
        } finally {
            this.options = {};
        }
    }
}
